package com.mezizy.ifanmerchant.global;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.mezizy.ifanmerchant.MainActivity;
import com.mezizy.ifanmerchant.NewOrderTab;
import com.mezizy.ifanmerchant.R;
import com.mezizy.ifanmerchant.global.com.mezizy.ifaner.web.data.Order;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.Timer;
import java.util.TimerTask;

public class GetNewOrderService extends Service {
    private static final String TAG = "GetNewOrderService";

    public static final String ACTION = "GetNewOrderService";
    public static int newOrderNum = -1;

    Handler handler = new Handler();
    NotificationManager mNotificationManager;
    NotificationCompat.Builder mBuilder;

    public PendingIntent getDefaultIntent(int flags) {
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, new Intent(getBaseContext(), MainActivity.class), flags);

        return pendingIntent;
    }


    public GetNewOrderService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    public void showNotification() {
        mNotificationManager.notify(0, mBuilder.build());
    }

    public void setNotification() {
        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        mBuilder = new NotificationCompat.Builder(getApplicationContext());

        mBuilder.setContentTitle("新订单")//设置通知栏标题
                .setContentText("点击查看新订单") //设置通知栏显示内容
                .setContentIntent(getDefaultIntent(Notification.FLAG_AUTO_CANCEL)) //设置通知栏点击意图
//  .setNumber(number) //设置通知集合的数量
                .setTicker("新订单来了！") //通知首次出现在通知栏，带上升动画效果的
                .setWhen(System.currentTimeMillis())//通知产生的时间，会在通知信息里显示，一般是系统获取到的时间
                .setPriority(Notification.PRIORITY_DEFAULT) //设置该通知优先级
                .setAutoCancel(true)//设置这个标志当用户单击面板就可以让通知将自动取消
                .setOngoing(false)//ture，设置他为一个正在进行的通知。他们通常是用来表示一个后台任务,用户积极参与(如播放音乐)或以某种方式正在等待,因此占用设备(如一个文件下载,同步操作,主动网络连接)
//                .setDefaults(Notification.DEFAULT_VIBRATE)//向通知添加声音、闪灯和振动效果的最简单、最一致的方式是使用当前的用户默认设置，使用defaults属性，可以组合
                        //Notification.DEFAULT_ALL  Notification.DEFAULT_SOUND 添加声音 // requires VIBRATE permission
                .setDefaults(Notification.DEFAULT_SOUND)
                .setSmallIcon(R.mipmap.ic_launcher);//设置通知小ICON
    }

    /*
    *   這個Method只會在第一次創建的時候執行只會startService不會執行，因此，Timer只會被執行一次。
    *
    * */
    @Override
    public void onCreate() {
        super.onCreate();

        //TODO test 之后移除 默认的商店ID
        Global.merchantId = "m001";
        Global.merchantPwdSha = "123";


        setNotification();
        Global.mNotificationManager = mNotificationManager;

        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                //TODO 从Server得到订单列表存放在Map中，计算Map中新订单的个数，如果个数增加了，就通知

                LinkedHashMap<String, Order> orderListMerchant = Global.getOrderListMerchant();


                if (orderListMerchant == null || orderListMerchant.entrySet() == null) {
                    return;
                }

                int newOrderNum = 0;
                for (Map.Entry<String, Order> stringOrderEntry : orderListMerchant.entrySet()) {
                    Order order = (Order) stringOrderEntry.getValue();
                    if (order == null) return;

                    int state = order.getTradeState();
                    if (state == Config.STATE_NOT_CONFIRM) newOrderNum++;

                }

//              GetNewOrderService.this.newOrderNum = -1 为第一次运行Server
                if (GetNewOrderService.this.newOrderNum != -1 && GetNewOrderService.this.newOrderNum < newOrderNum) {

                    if (Global.appState == Config.BACKGROUND) {
                        showNotification();
                        Log.i(TAG, "GET MESSAGE");
                        handler.post(new Runnable() {
                            @Override
                            public void run() {

                            }
                        });
                    } else if (Global.appState == Config.FOREGROUND) {
                        //TODO * 更新MainActivity (用廣播)
                        Intent intent = new Intent();
                        intent.setAction(Config.ACTION_NEW_ORDER);
                        sendBroadcast(intent);
                    }

                }
                GetNewOrderService.this.newOrderNum = newOrderNum;

                /*handler.post(new Runnable() {
                    @Override
                    public void run() {

                    }
                });*/

            }
        }, 0, Config.GET_NEW_ORDER_SERVER_REPEAT_TIME);


    }
}
